require('dotenv').config();
const express = require('express');
const pool = require('./db');
const midianalyse = require('./ai/midianalyse');
const nltranslate = require('./ai/nltranslate');

const app = express();
const port = process.env.PORT || 3000;


app.use(express.json()); // 用于解析application/json类型的数据
app.use(express.urlencoded({ extended: true })); // 用于解析application/x-www-form-urlencoded类型的数据

app.post('/launch', async (req, res) => {
  res.json({errcode: process.env.ERRCODE_OK, data: {script: ''}});
});

app.post('/upload-error-log', async (req, res) => {
  // console.log(req);
  const body = req.body;
  console.log(body);
  const logData = Buffer.from(body.data, 'base64').toString('utf-8');
  const dml = "insert into t_client_error_trace(fuserid, fdata, fdeviceId, fdeviceName, fsystemVersionCode, fversionCode, flaunchId, fip) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) returning fid";
  const values = [body.userid, logData, body.device_id, body.device_name, body.system_version_code, body.version_code, body.launch_id, req.ip];
  res.json({errcode: process.env.ERRCODE_OK, errmsg: ""});
  pool.query(dml, values, (err, dbres) => {
    if (err) {
      console.error(err);
    }
    else {
      console.log('Data inserted:', dbres.rows);
    }
  });
});

// 数据库查询示例
app.post('/get-time', async (req, res) => {
  pool.query('SELECT NOW() AS current_time',(err, dbres) => {
    if (err) {
      console.error(err);
      res.json({ errcode: process.env.ERRCODE_FAIL, errmsg: err.toString() });
    }
    else {
      res.json({ errcode: process.env.ERRCODE_OK, time: dbres.rows[0].current_time });
    }
  });
});

app.post('/create-user', async (req, res) => {
  // console.log(req);
  const body = req.body;
  const data = body.data;
  const dml = "insert into t_user(fname, fdevicename, fphonenum, fforbid, fdeviceid, fcreateip) VALUES ($1, $2, $3, $4, $5, $6) returning fid";
  const values = [data.name, data.device_name, data.phone_num, 0, data.device_id, req.ip];
  pool.query(dml, values, (err, dbres) => {
    if (err) {
      console.error(err);
      res.json({errcode: process.env.ERRCODE_FAIL, errmsg: err.toString()});
    }
    else {
      console.log('Data inserted:', dbres.rows);
      res.json({errcode: process.env.ERRCODE_OK, data: dbres.rows[0].fid});
    }
  });
})

app.post('/create-user', async (req, res) => {
  // console.log(req);
  const body = req.body;
  const data = body.data;
  const dml = "insert into t_user(fname, fdevicename, fphonenum, fforbid, fdeviceid, fcreateip) VALUES ($1, $2, $3, $4, $5, $6) returning fid";
  const values = [data.name, data.device_name, data.phone_num, 0, data.device_id, req.ip];
  pool.query(dml, values, (err, dbres) => {
    if (err) {
      console.error(err);
      res.json({errcode: process.env.ERRCODE_FAIL, errmsg: err.toString()});
    }
    else {
      console.log('Data inserted:', dbres.rows);
      res.json({errcode: process.env.ERRCODE_OK, data: dbres.rows[0].fid});
    }
  });
})

app.post('/translate', async (req, res) => {
  // console.log(req);
  const body = req.body;
  console.log('/translate body: ', body);
  let values;
  try {
    const traslate_ret = await nltranslate.translate(body.text, body.from, body.to);
    console.log(traslate_ret);
    res.json({errcode: traslate_ret.retcode, data: traslate_ret.translate_text, errmsg: traslate_ret.retmsg});
  } catch (err) {
    console.error('freeplay-mididata-analyse AI分析失败:', err);
    res.status(500).json({errcode: process.env.ERRCODE_FAIL, errmsg: "服务内部错误"});
    return;
  }

})

app.post('/freeplay-mididata-analyse', async (req, res) => {
  // console.log(req);
  const body = req.body;
  console.log('/freeplay-mididata-analyse body: ', body);
  let values;
  try {
    const analyse_data = await midianalyse.analyse(body.userid, body.data);
    console.log(analyse_data);
    res.json({errcode: analyse_data.retcode, data: analyse_data.airesponse, errmsg: analyse_data.retmsg});


    values = [body.userid, analyse_data.request, analyse_data.airesponse, analyse_data.tokens, analyse_data.retcode];
  } catch (err) {
    console.error('freeplay-mididata-analyse AI分析失败:', err);
    res.status(500).json({errcode: process.env.ERRCODE_FAIL, errmsg: "服务内部错误"});
    return;
  }

  const dml = "insert into t_freeplay_ai_analyse (fuserid, frequestmididata, fairesponsedata, faitokens, fairetcode) VALUES ($1, $2, $3, $4, $5)";
  pool.query(dml, values, (err, dbres) => {
    if (err) {
      console.error(err);
    }
    else {
      console.log('Data inserted:', dbres.rows);
    }
  });
})

// 全局错误处理（添加到所有路由之后）
app.use((err, req, res, next) => {
    console.error('全局捕获:', err);
    res.status(500).json({errcode: process.env.ERRCODE_FAIL, errmsg: "服务异常"});
});

// 确保所有数据库操作都有错误响应
pool.on('error', (err) => {
  console.error('数据库连接池错误:', err);
});


process.on('beforeExit', (code) => {
  console.log('进程即将退出，代码:', code);
});

process.on('unhandledRejection', (err) => {
  console.error('Unhandled Rejection:', err);
});

process.on('uncaughtException', (err) => {
  console.error('未捕获异常:', err);
});

process.on('SIGTERM', () => {
  console.log('Received SIGTERM, cleaning up...');
  server.close(() => process.exit(0));
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});